﻿/*
COPYRIGHT (C) 2009 EPISERVER AB

THIS FILE IS PART OF MAPPED PAGE PROVIDER FOR EPISERVER CMS.
MAPPED PAGE PROVIDER FOR EPISERVER CMS IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

MAPPED PAGE PROVIDER FOR EPISERVER CMS IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER GENERAL PUBLIC LICENSE FOR MORE DETAILS.
YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH MAPPED PAGE PROVIDER FOR EPISERVER CMS. IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using EPiServer.DataAccess;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.CompilerServices;

namespace EPiServer.Research.PageProviders
{
	public class MappedPPDB : DataAccessBase
	{
		private static MappedPPDB _instance;
		private static object _instanceLock = new object();
		private Dictionary<string, PageProviderCache> _cachedMappings;

		public static MappedPPDB Instance
		{
			get
			{
				if (_instance == null)
				{
					lock (_instanceLock)
					{
						if (_instance == null)
						{
							_instance = new MappedPPDB();
						}
					}
				}
				return _instance;
			}
		}

		protected PageProviderMapping GetFromCache(string providerName, string key)
		{
			if (!_cachedMappings.ContainsKey(providerName))
			{
				return null;
			}
			return _cachedMappings[providerName].GetFromCache(key);
		}

		protected void RemoveFromCache(string providerName, string key)
		{
			if (_cachedMappings.ContainsKey(providerName))
			{
				_cachedMappings[providerName].RemoveFromCache(LoadMapping(providerName, key));
			}
		}

		protected PageProviderMapping GetFromCache(string providerName, int id)
		{
			if (!_cachedMappings.ContainsKey(providerName))
			{
				return null;
			}
			return _cachedMappings[providerName].GetFromCache(id);

		}

		protected void RemoveFromCache(string providerName, int id)
		{
			if (_cachedMappings.ContainsKey(providerName))
			{
				_cachedMappings[providerName].RemoveFromCache(LoadMapping(providerName, id));
			}
		}
	
		protected PageProviderMapping GetFromCache(string providerName, Guid guid)
		{
			if (!_cachedMappings.ContainsKey(providerName))
			{
				return null;
			}
			return _cachedMappings[providerName].GetFromCache(guid);
		}

		protected void RemoveFromCache(string providerName, Guid guid)
		{
			if (_cachedMappings.ContainsKey(providerName))
			{
				_cachedMappings[providerName].RemoveFromCache(LoadMapping(providerName, guid));
			}
		}

		[MethodImpl(MethodImplOptions.Synchronized)]
		protected void AddToCache(string providerName, PageProviderMapping providerMapping)
		{
			if (!_cachedMappings.ContainsKey(providerName))
			{
				_cachedMappings.Add(providerName, new PageProviderCache());
			}
			_cachedMappings[providerName].AddToCache(providerMapping);
		}

		public MappedPPDB()
		{
			CreateIfNotExist();
			_cachedMappings = new Dictionary<string, PageProviderCache>();
		}

		[MethodImpl(MethodImplOptions.Synchronized)]
		protected PageProviderMapping LoadMapping(string providerName, string clause, object param)
		{

			PageProviderMapping pageProviderMapping = base.Execute<PageProviderMapping>(delegate
			{
				string sql = "SELECT PageKey, PageID, PageGuid FROM tblPageProviderMappings WHERE ProviderID=@ProviderName AND " + clause + "=@Param";
				IDbCommand command = base.CreateTextCommand(sql);
				command.Parameters.Add(base.CreateParameter("ProviderName", providerName));
				command.Parameters.Add(base.CreateParameter("Param", param));

				IDataReader reader = command.ExecuteReader(CommandBehavior.SingleResult);
				if (reader.Read())
				{
					return new PageProviderMapping()
											{
												Id = (int)reader["PageID"],
												Key = (string)reader["PageKey"],
												Guid = (Guid)reader["PageGuid"]
											};
				}
				return null;
			});
			if ((pageProviderMapping == null) && (clause == "PageKey"))
			{
				return AddKey(providerName, (string)param);
			}
			return pageProviderMapping;
		}


		public void RemoveId(string providerName, int id)
		{
			PageProviderMapping mapping = LoadMapping(providerName, id);
			if (mapping != null)
			{
				DeleteMapping(providerName, mapping.Key);
			}
		}

		public PageProviderMapping AddKey(string providerName, string key)
		{
			PageProviderMapping pageProviderMapping = new PageProviderMapping();
			pageProviderMapping.Key = key;
			pageProviderMapping.Guid = Guid.NewGuid();
			int maxId = base.Execute<int>(delegate
			{
				IDbCommand cmd = base.CreateTextCommand("SELECT MAX(PageID) FROM tblPageProviderMappings WHERE ProviderID=@Provider");
				cmd.Parameters.Add(base.CreateParameter("Provider", providerName));
				object o = cmd.ExecuteScalar();
				int maxID = 0;
				if (o != null && o != DBNull.Value)
				{
					maxID = (int)o;
				}
				return maxID;
			});
			pageProviderMapping.Id = maxId + 1;

			base.Execute(delegate
			{
				IDbCommand cmd2 = base.CreateTextCommand("INSERT INTO tblPageProviderMappings (ProviderID,PageKey,PageID,PageGuid) VALUES (@ProviderID,@PageKey,@PageID, @PageGuid)");
				cmd2.Parameters.Add(base.CreateParameter("ProviderID", providerName));
				cmd2.Parameters.Add(base.CreateParameter("PageKey", pageProviderMapping.Key));
				cmd2.Parameters.Add(base.CreateParameter("PageID", pageProviderMapping.Id));
				cmd2.Parameters.Add(base.CreateParameter("PageGuid", pageProviderMapping.Guid));
				cmd2.ExecuteNonQuery();
			});
			return pageProviderMapping;
		}

		public PageProviderMapping LoadMapping(string providerName, Guid guid)
		{
			PageProviderMapping providerMapping = GetFromCache(providerName, guid);
			if (providerMapping != null)
			{
				return providerMapping;
			}
			providerMapping = LoadMapping(providerName, "PageGuid", guid);
			if (providerMapping != null)
			{
				AddToCache(providerName, providerMapping);
			}
			return providerMapping;
		}

		public PageProviderMapping LoadMapping(string providerName, int id)
		{
			PageProviderMapping providerMapping = GetFromCache(providerName, id);
			if (providerMapping != null)
			{
				return providerMapping;
			}
			providerMapping = LoadMapping(providerName, "PageID", id);
			if (providerMapping != null)
			{
				AddToCache(providerName, providerMapping);
			}
			return providerMapping;
		}

		public PageProviderMapping LoadMapping(string providerName, string key)
		{
			PageProviderMapping providerMapping = GetFromCache(providerName, key);
			if (providerMapping != null)
			{
				return providerMapping;
			}
			providerMapping = LoadMapping(providerName, "PageKey", key);
			if (providerMapping != null)
			{
				AddToCache(providerName, providerMapping);
			}
			return providerMapping;
		}

		public void DeleteMapping(string providerName, string key)
		{
			base.Execute(delegate
			{
				IDbCommand cmd = base.CreateTextCommand(string.Format("DELETE FROM tblPageProviderMappings WHERE ProviderID='{0}' AND PageKey='{1}'", providerName, key));
				//cmd.Parameters.Add(base.CreateTextParameter("Provider", providerName));
				//cmd.Parameters.Add(base.CreateTextParameter("Key", key));
				cmd.ExecuteNonQuery();
			});
			RemoveFromCache(providerName, key);
		}

		protected void CreateIfNotExist()
		{
			bool exist = base.Execute<bool>(delegate
			{
				IDbCommand cmd = base.CreateCommand("select count(name) from sysobjects where xtype='u' and name = 'tblPageProviderMappings'");
				cmd.CommandType = CommandType.Text;
				int v = (int)cmd.ExecuteScalar();
				return (v == 1);
			});

			if (!exist)
			{
				base.Execute(delegate
				{
					string create = "CREATE TABLE [dbo].[tblPageProviderMappings](" +
											"[ProviderID] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL," +
											"	[PageKey] [varchar](256) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL," +
											"	[PageID] [int] NOT NULL," +
											"	[PageGuid] [uniqueidentifier] NOT NULL," +
											" CONSTRAINT [PK_tblPageProviderMappings] PRIMARY KEY CLUSTERED " +
											"(" +
											"	[ProviderID] ASC," +
											"	[PageKey] ASC" +
											")WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]" +
											") ON [PRIMARY]";
					IDbCommand cmd = base.CreateTextCommand(create);
					cmd.ExecuteNonQuery();
				});
			}
		}
	}
}